﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace GMS.Client.Utility
{
    /// <summary>
    /// 进程辅助类
    /// </summary>
    public class ProcessHelper
    {
        /// <summary>
        /// 启动进程
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="workingDirectory"></param>
        public static IntPtr Start(string fileName, string workingDirectory)
        {
            var processStartInfo = new ProcessStartInfo();
            processStartInfo.FileName = fileName;
            processStartInfo.WorkingDirectory = workingDirectory;
            processStartInfo.WindowStyle = ProcessWindowStyle.Normal;
            return Process.Start(processStartInfo).MainWindowHandle;
        }

        /// <summary>
        /// 查找进程
        /// </summary>
        /// <param name="processName"></param>
        /// <returns></returns>
        public static bool Find(string processName)
        {
            var processList = Process.GetProcessesByName(processName);
            return processList.Count() > 0;
        }

        /// <summary>
        /// 查找进程
        /// </summary>
        /// <param name="processName"></param>
        /// <returns></returns>
        public static IntPtr Find(string processName, string workingPath)
        {
            var handle = IntPtr.Zero;
            var processList = Process.GetProcessesByName(processName);
            processList.ToList().ForEach(p =>
            {
                if (p.MainModule.FileName == workingPath)
                {
                    handle = p.MainWindowHandle;
                }
            });
            return handle;
        }

        /// <summary>
        /// 杀死进程
        /// </summary>
        /// <param name="processName"></param>
        public static void Kill(string processName, string workingPath)
        {
            var processList = Process.GetProcessesByName(processName);
            processList.ToList().ForEach(p =>
            {
                if (p.MainModule.FileName == workingPath)
                {
                    p.Kill();
                }
            });
        }
    }
}
